package com.jiang.jixiang.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.MalfunctionFailBean;
import com.jiang.jixiang.databinding.ActivityMalfunctionBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.jiang.jixiang.tools.UrlParse;
import com.jiang.jixiang.ui.adapter.MalfunctionFailAdapter;
import com.jiang.jixiang.ui.adapter.MalfunctionUploadAdapter;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.permission.AppActivityTarget;
import com.ws.universal.tools.permission.PermissionListener;
import com.ws.universal.tools.permission.SettingExecutor;
import com.ws.universal.tools.takephoto.app.TakePhoto;
import com.ws.universal.tools.takephoto.app.TakePhotoImpl;
import com.ws.universal.tools.takephoto.model.InvokeParam;
import com.ws.universal.tools.takephoto.model.TContextWrap;
import com.ws.universal.tools.takephoto.model.TImage;
import com.ws.universal.tools.takephoto.model.TResult;
import com.ws.universal.tools.takephoto.permission.InvokeListener;
import com.ws.universal.tools.takephoto.permission.PermissionManager;
import com.ws.universal.tools.takephoto.permission.TakePhotoInvocationHandler;
import com.ws.universal.tools.utils.BitmapUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.PermissionUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 故障维修
 */
public class MalfunctionActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener, NetWorkListener {
    private ActivityMalfunctionBinding binding;
    private MalfunctionFailAdapter malfunctionFailAdapter;
    private List<MalfunctionFailBean> list;
    private MalfunctionUploadAdapter malfunctionUploadAdapter;//上传图片
    private String imgs = "";
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private int position = 0;
    private JSONObject data;
    private int indexPostion = 0;
    private int requestCodeCamera = 10005;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    @Override
    protected void initCreate(Bundle savedInstanceState) {
        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        getTakePhoto().onCreate(savedInstanceState);
        binding = ActivityMalfunctionBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EventBusUtil.resgisterEventBus(this);
    }

    @Override
    protected void initView() {

        binding.inTitle.titleTextTv.setText(R.string.fault_feedback);
        binding.inTitle.titleLeftBtn.setOnClickListener(view -> {
            finish();
        });

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }

            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        binding.rcyData.setLayoutManager(linearLayoutManager);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3) {
            @Override
            public boolean canScrollHorizontally() {
                return false;
            }

            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        //binding.rcyDataImage.addItemDecoration(new SpacesItemDecortion(10, 3));
        binding.rcyDataImage.setLayoutManager(gridLayoutManager);


        malfunctionFailAdapter = new MalfunctionFailAdapter();
        list = new ArrayList<>();
        binding.rcyData.setAdapter(malfunctionFailAdapter);
        list.add(new MalfunctionFailBean(getString(R.string.the_power_bank_cannot_pop_up_normally), false));
        list.add(new MalfunctionFailBean(getString(R.string.damaged_charging_cable), true));
        list.add(new MalfunctionFailBean(getString(R.string.qr_code_abnormal), false));
        list.add(new MalfunctionFailBean(getString(R.string.other), false));

        malfunctionFailAdapter.addData(list);

        malfunctionFailAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                toggleSelection(malfunctionFailAdapter, position);

            }
        });


        malfunctionUploadAdapter = new MalfunctionUploadAdapter();
        binding.rcyDataImage.setAdapter(malfunctionUploadAdapter);

        malfunctionUploadAdapter.getData().add(BitmapUtils.getPath(getContext(), "icon_upload.png"));

        malfunctionUploadAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                switch (view.getId()) {
                    case R.id.imgItemAdd:
                        if (malfunctionUploadAdapter.getData().size() < 4 && position == malfunctionUploadAdapter.getData().size() - 1) {

                            PermissionUtils.getInstance().CheckPermissions(new PermissionListener() {
                                @Override
                                public void onPermissionSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                    // if (fatherActivity != null)
                                    PubDiaUtils.getInstance().showSelectImgDialog(getSupportFragmentManager(),
                                            getContext(), takePhoto, 4 - malfunctionUploadAdapter.getData().size(), false, false);
                                }

                                @Override
                                public void onPermissionFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                                    PubDiaUtils.getInstance().showTwoBtnDialog(getContext(), getString(R.string.permission_hit), getString(R.string.permission_content), getString(R.string.cancel), getString(R.string.sure), new PubDiaUtils.PublicDiaologCallback() {
                                        @Override
                                        public void onConfirm() {
                                            if (mSettingService == null) {
                                                mSettingService = new SettingExecutor(new AppActivityTarget(getActivity()), 300);
                                            }
                                            mSettingService.execute();
                                        }

                                        @Override
                                        public void onCancel() {

                                        }
                                    });
                                }
                            }, requestCodeCamera, PermissionUtils.Permission_File);
                        }
                        break;
                    case R.id.imgItemClose:
                        Iterator<String> iterator = malfunctionUploadAdapter.getData().iterator();
                        while (iterator.hasNext()) {
                            String bean = iterator.next();
                            //LogcatUtils.i(" "+bean.path);
                            if (bean.equals(malfunctionUploadAdapter.getData().get(position))) {
                                iterator.remove();//使用迭代器的删除方法删除
                                break;
                            }
                        }
                        malfunctionUploadAdapter.notifyDataSetChanged();
                        break;
                }
            }
        });

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getData() != null && result.getResultCode() == Activity.RESULT_OK) {
                    String resultScanCode = result.getData().getStringExtra("resultScanCode");
                    if (resultScanCode.indexOf("https://charge8.w-dian.cn/Lease?o=l58=&&") > -1) {
                        Map<String, String> urlParams = UrlParse.getUrlParams(resultScanCode);
                        binding.searchView.setText(urlParams.get("t"));
                    } else {
                        ToastUtils.showShort(getText(R.string.qr_code_abnormal));
                    }


                }
            }

        });
        binding.Submit.setChangeAlphaWhenPress(true);
        binding.Submit.setOnClickListener(view -> {
            if (malfunctionUploadAdapter.getData().size() > 1) {
                showProgressDialog(false);
                imgs = "";
                indexPostion = 0;
                upLoadFile();
            } else {
                subMit();
            }


        });
    }

    private void upLoadFile() {
        ArrayList<File> files = new ArrayList<>();
        files.add(new File(malfunctionUploadAdapter.getData().get(indexPostion)));
        okHttpModel.postUpLoadFile(ApiUrl.fileUpload_Api, files, ApiUrl.fileUpload_Api_ID, this);
    }

    private void subMit() {
        if (TextUtils.isEmpty(binding.searchView.getText().toString())) {
            ToastUtils.showShort(getString(R.string.device_code_cannot_be_empty));
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("device_code", binding.searchView.getText().toString());
        params.put("remark", binding.edRemard.getText().toString());
        params.put("content", StringUtils.getString(position));
        if (!TextUtils.isEmpty(imgs)) {
            params.put("imgs", imgs);

        }
        okHttpModel.post(ApiUrl.userAppeal_Api, params, ApiUrl.userAppeal_Api_ID, this);

    }

    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.userAppeal_Api_ID:
                stopProgressDialog();
                ToastUtils.showShort(commonality.getMessage());
                finish();
                break;
            case ApiUrl.fileUpload_Api_ID:
                imgs = imgs + StringUtils.getString(commonality.getMessage(), ",");
                LogcatUtils.e(" listUpLoad " + imgs);
                indexPostion++;
                if (indexPostion == malfunctionUploadAdapter.getData().size() - 1) {
                    subMit();
                } else {
                    upLoadFile();
                }

                break;
        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }


    private void toggleSelection(MalfunctionFailAdapter adapter, int position) {

        //单选
        for (int i = 0; i < adapter.getData().size(); i++) {
            if (i == position) {
                adapter.getData().get(position).setCheck(true);
            } else {
                adapter.getData().get(i).setCheck(false);
            }
        }
        this.position = position;
        adapter.notifyDataSetChanged();
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    private void showImg(ArrayList<TImage> images) {
        for (int i = 0; i < images.size(); i++) {
            malfunctionUploadAdapter.getData().add(0, images.get(i).getCompressPath());
        }
        malfunctionUploadAdapter.notifyDataSetChanged();


    }


    @Override
    public void takeSuccess(TResult result) {
        showImg(result.getImages());

    }


    @Override
    public void takeFail(TResult result, String msg) {

    }

    @Override
    public void takeCancel() {

    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }


    @Subscribe(threadMode = ThreadMode.MAIN)  //3.0之后，需要加注解
    public void onEventMainThread(BaseBusData data) {
        switch (data.action) {
            case BusCode.inputDeviceNum:
                binding.searchView.setText(data.str);
                break;

        }

    }


    @Override
    protected void FinishDesTroy() {
        EventBusUtil.unResgisterEventBus(this);
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }
}
